#include <stdio.h>
#include <dirent.h>
#include <unistd.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "server.h"

int create_socket(int port) {

    int sd;
    struct sockaddr_in dir_srv;
    /* Creo un descriptor de archivo. */
    if ((sd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
        return (-1);

    /* Hago un bind de la direccion local */
    bzero((char *) & dir_srv, sizeof (dir_srv));
    dir_srv.sin_family = AF_INET;
    dir_srv.sin_addr.s_addr = htonl(INADDR_ANY);
    dir_srv.sin_port = htons(port);

    if (bind(sd, (struct sockaddr *) & dir_srv, sizeof (dir_srv)) < 0)
        return (-2);

    return sd;
}

int main(int argc, char *argv[]) {
    if (read_conf() == ERROR) {
        perror("No se ha podido leer el archivo de configuración del Servidor. Se aborta la operación.\n");
        exit(1);
    };
    // Inicializo el servidor.
    if ((sd = create_socket(port)) < 0) {
        perror("ERROR INICIALZANDO SERVIDOR: ");
        exit(-1);
    }
    printf("Servidor inicializado.\n");

    PACKAGE *package = malloc(sizeof (PACKAGE));
    struct sockaddr_in from;
    int fromlen = sizeof (from);

    while (1) {
        /* Read from the socket */
        recvfrom(sd, package, sizeof (PACKAGE), 0, (struct sockaddr *) &from, &fromlen);
        package->to = sd;

        switch (package->op) {
            case RLS:
                rls(package, from);
                break;
            case RCD:
                rcd(package, from);
                break;
            case GET:
                get(package, from);
                break;
            case PUT:
                put(package, from);
                break;
            default:
                exit(0);
        }
    }
}
